import dbus, gobject

from dbus.mainloop.glib import DBusGMainLoop

DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()

def gen_message():
  from os import popen
  x = popen('fortune')
  message = '\n[ROBOT]\n';
  for line in x.readlines():
    message += line
    #y = popen('tweet  [test dbus] '+line)
  return message+"[ROBOT]\n"

def sent_fortune_message(account,sender):
  obj = bus.get_object("im.pidgin.purple.PurpleService",
	    "/im/pidgin/purple/PurpleObject")
  purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
  conv = purple.PurpleConversationNew(1,account, sender)
  im = purple.PurpleConvIm(conv)
  message = gen_message()
  purple.PurpleConvImSend(im, message)

def received_response(account, sender, message, conversation, flags):
  print '----------------------------------------------'
  print "received from (%s) : %s" %(sender, message)
  sent_fortune_message(account,sender)
  
def sent_response(account, receiver, message):
  print '----------------------------------------------'
  print 'sent to (%s) : %s' %(receiver, message)

bus.add_signal_receiver(received_response,
  dbus_interface='im.pidgin.purple.PurpleInterface',
  signal_name='ReceivedImMsg')
  
bus.add_signal_receiver(sent_response,
  dbus_interface='im.pidgin.purple.PurpleInterface',
  signal_name="SentImMsg")
  
loop = gobject.MainLoop()
loop.run()
